from flask import Flask, render_template, request, redirect, url_for

app=Flask(__name__)


students=[
    {"sid":1,"name":"张三","gender":"男","age":18,"s_class":"13班","email":"123qq@.com","dress":"地球"},
    {"sid":2,"name":"李四","gender":"男","age":18,"s_class":"13班","email":"123qq@.com","dress":"地球"},
    {"sid":3,"name":"小明","gender":"男","age":18,"s_class":"13班","email":"123qq@.com","dress":"地球"},
    {"sid":4,"name":"小红","gender":"男","age":18,"s_class":"13班","email":"123qq@.com","dress":"地球"},
    {"sid":250,"name":"姜林辰","gender":"女","age":99,"s_class":"250班","email":"250qq@.com","dress":"250家"}
]

@app.route("/list")
def list():
    search_name=request.args.get("search")
    filter_students=[]
    if search_name:
        for stu in students:
            if search_name in stu.get("name"):
                filter_students.append(stu)
        return render_template("list.html",students=filter_students)
    return render_template("list.html",students=students)

@app.route("/add",methods=["get","post"])
def add():
    error=None
    # 如果是post请求的时候，进行新增的逻辑处理
    if request.method=="POST":
        sid =request.form.get("sid")
        name =request.form.get("name")
        gender =request.form.get("gender")
        age =request.form.get("age")
        s_class =request.form.get("s_class")
        email =request.form.get("email")
        dress =request.form.get("dress")
        # 进行重复性和输入有效性判断
        try:
            int_sid=int(sid)
            if int_sid  in [stu.get("sid") for stu in students]:
                error="学号重复了"
        except:
            error= "用户输入的学号出现错误"
        try:
            int_age=int(age)
            if int_age < 0 or int_age > 200:
                error = "用户输入的年龄超出限制"
        except:
            error= "用户输入的年龄出现错误"
        if not error:
            dic ={"sid":sid,"name":name,"gender":gender,"age":age,"s_class":s_class,"email":email,"dress":dress}
            students.append(dic)
            return redirect(url_for("list"))
     # 如果post发生了错误，则在if not error:判断异常，此时不会跳转到list路由，进入到该逻辑
     # 若果用户发起的是get请求，则直接发起add页面的渲染，此时的error为空
    return render_template("add.html",error=error)

@app.route("/modify/<int:sid>",methods=["get","post"])
def modify(sid):
    # for stu in students:
    #     if str(sid) == str(stu.get("sid")):
    #         student=stu
    student=next(iter([stu for stu in students if str(sid) == str(stu.get("sid"))]),{})
    if not student:
        return f"学员信息找不到",404
    error=None
    if request.method == "POST":
        name = request.form.get("name")
        gender = request.form.get("gender")
        age = request.form.get("age")
        s_class = request.form.get("s_class")
        email = request.form.get("email")
        dress = request.form.get("dress")

        try:
            int_sid = int(sid)
            if int_sid  in [stu.get("sid") for stu in students]:
                error = "学号重复了"
        except:
            error = "用户输入的学号出现错误"
        try:
            int_age = int(age)
            if int_age < 0 or int_age > 200:
                error = "用户输入的年龄超出限制"
        except:
            error = "用户输入的年龄出现错误"
        if not error:
            student["name"]=name
            student["gender"]=gender
            student["age"]=age
            student["s_class"]=s_class
            student["email"]=email
            student["dress"]=dress
            return redirect(url_for("list"))  #url_for(视图函数名) 即可返回对应视图函数的 url
    # 若果用户发起的是get请求，则直接发起add页面的渲染（render_template），此时的error为空
    return render_template("modify.html",student=student,error=error)

@app.route("/delete/<int:sid>")
def delete(sid):
    global students
    students=[stu for stu in students if str(stu.get("sid")) != str(sid)]
    return render_template("list.html",students=students)

if __name__ == '__main__':
    app.run(host="0.0.0.0",debug=True,port=5000)